//
//  BSWebViewController.m
//  BaiSi
//
//  Created by Sycamore on 16/5/2.
//  Copyright © 2016年 Sycamore. All rights reserved.
//

#import "BSWebViewController.h"
#import <WebKit/WebKit.h>

@interface BSWebViewController ()
@property (weak, nonatomic) IBOutlet UIView *webContainView;

@property (nonatomic,weak) WKWebView *webView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *fowordButton;

@end

@implementation BSWebViewController
- (IBAction)back:(UIBarButtonItem *)sender {
    
    [_webView goBack];
}
- (IBAction)gofoword:(id)sender {
    [_webView goForward];
}
- (IBAction)refresh:(id)sender {
    [_webView reload];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_url]];
    
    [webView loadRequest:request];
    
    _webView = webView;
    
    [_webContainView addSubview:webView];
    
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew  context: nil];
    
}


- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:@"title"];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"canGoBack"];
    [_webView removeObserver:self forKeyPath:@"canGoForward"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    _progressView.progress = _webView.estimatedProgress;
    _progressView.hidden = _progressView.progress >= 1;
    self.navigationItem.title = _webView.title;
    
    _backButton.enabled = _webView.canGoBack;
    _fowordButton.enabled = _webView.canGoForward;
}

@end
